import React, { useState, useEffect, useReducer, useLayoutEffect, useContext } from 'react'

import MyContext from '../../lib/my-context'

class MyCount extends React.Component {
  state = {
    count: 0
  }

  componentDidMount() {
    this.interval = setInterval(() => {
      this.setState({
        count: this.state.count + 1
      })
    }, 1000)
  }

  componentWillUnmount() {
    if (this.interval) {
      clearInterval(this.interval)
    }
  }

  render() {
    return <h1>{this.state.count}</h1>
  }
}

function countReducer(state, action) {
  switch (action.type) {
    case 'add':
      return state + 1
    case 'minus':
      return state - 1
    default:
      return state
  }
}

function MyCountFunc() {
  // const [count, setCount] = useState(0)
  const [count, dispatchCount] = useReducer(countReducer, 0)
  const [name, setName] = useState('react')

  const context = useContext(MyContext)

  // useEffect(() => {
  //   const interval = setInterval(() => {
  //     // setCount(c => c + 1)
  //     dispatchCount({ type: 'add' })
  //   }, 1000)
  //   return () => clearInterval(interval)
  // }, [])

  useEffect(() => {
    console.log('effect in')
    return () => {
      console.log('effect return')
    }
  }, [count])

  // 
  useLayoutEffect(() => {
    console.log('useLayoutEffect in')
    return () => {
      console.log('useLayoutEffect return')
    }
  }, [count])

  return (
    <div>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={() => dispatchCount({ type: 'add' })}>{count}</button>
      <h3>{context}</h3>
    </div>
  )
}

export default MyCountFunc